import React, { useEffect, useState } from 'react';
import { dbManager, ChatRecord, ChatMessage } from '../utils/indexedDB';

const ChatStore: React.FC = () => {
    const [chats, setChats] = useState<ChatRecord[]>([]);
    const [loading, setLoading] = useState(true);
    const [message, setMessage] = useState('');
    const [selectedChatId, setSelectedChatId] = useState<string | null>(null);

    // 初始化并加载聊天记录
    useEffect(() => {
        const initAndLoad = async () => {
            try {
                await dbManager.initDB();
                await loadChats();
            } catch (error) {
                console.error('初始化或加载失败:', error);
            } finally {
                setLoading(false);
            }
        };

        initAndLoad();

        // 组件卸载时关闭数据库连接
        return () => {
            dbManager.closeDB();
        };
    }, []);

    // 加载所有聊天记录
    const loadChats = async () => {
        const allChats = await dbManager.getAllChats();
        setChats(allChats);
    };

    // 创建新聊天
    const createNewChat = async () => {
        const newChat: ChatRecord = {
            chatId: Date.now().toString(),
            messages: [],
            model: 'deepseek-r1',
            title: `新会话 ${new Date().toLocaleString()}`,
            desc: ''
        };

        await dbManager.addChat(newChat);
        await loadChats();
        setSelectedChatId(newChat.chatId);
    };

    // 删除聊天
    const deleteChat = async (chatId: string) => {
        await dbManager.deleteChat(chatId);
        await loadChats();
        if (selectedChatId === chatId) {
            setSelectedChatId(null);
        }
    };

    // 发送消息
    const sendMessage = async () => {
        if (!selectedChatId || !message.trim()) return;

        const userMessage: ChatMessage = {
            role: 'user',
            content: message,
            timestamp: Date.now()
        };

        await dbManager.addMessageToChat(selectedChatId, userMessage);

        // 模拟AI回复
        const aiMessage: ChatMessage = {
            role: 'assistant',
            content: `这是对"${message}"的回复`,
            timestamp: Date.now()
        };

        await dbManager.addMessageToChat(selectedChatId, aiMessage);
        setMessage('');
        await loadChats();
    };

    // 获取当前选中的聊天
    const selectedChat = chats.find(chat => chat.chatId === selectedChatId);

    if (loading) {
        return <div>正在加载数据库...</div>;
    }

    return (
        <div className="chat-store" style={{ display: 'flex', height: '100vh' }}>
            {/* 左侧聊天列表 */}
            <div style={{ width: '250px', borderRight: '1px solid #eee', padding: '10px' }}>
                <button
                    onClick={createNewChat}
                    style={{ width: '100%', padding: '8px', marginBottom: '10px' }}
                >
                    新建聊天
                </button>

                <div>
                    {chats.length === 0 ? (
                        <div style={{ textAlign: 'center', padding: '20px' }}>没有聊天记录</div>
                    ) : (
                        <ul style={{ listStyle: 'none', padding: 0 }}>
                            {chats.map(chat => (
                                <li
                                    key={chat.chatId}
                                    style={{
                                        padding: '10px',
                                        margin: '5px 0',
                                        cursor: 'pointer',
                                        backgroundColor: selectedChatId === chat.chatId ? '#f0f0f0' : 'transparent',
                                        borderRadius: '5px',
                                        display: 'flex',
                                        justifyContent: 'space-between'
                                    }}
                                    onClick={() => setSelectedChatId(chat.chatId)}
                                >
                                    <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                        {chat.title || `聊天 ${chat.chatId}`}
                                    </div>
                                    <button
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            deleteChat(chat.chatId);
                                        }}
                                        style={{ marginLeft: '5px' }}
                                    >
                                        删除
                                    </button>
                                </li>
                            ))}
                        </ul>
                    )}
                </div>
            </div>

            {/* 右侧聊天界面 */}
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '10px' }}>
                {selectedChat ? (
                    <>
                        <div style={{ marginBottom: '10px' }}>
                            <h2>{selectedChat.title || `聊天 ${selectedChat.chatId}`}</h2>
                            <div>模型: {selectedChat.model}</div>
                        </div>

                        {/* 聊天消息区域 */}
                        <div style={{ flex: 1, overflow: 'auto', border: '1px solid #eee', borderRadius: '5px', padding: '10px', marginBottom: '10px' }}>
                            {selectedChat.messages.length === 0 ? (
                                <div style={{ textAlign: 'center', marginTop: '20px', color: '#888' }}>
                                    没有消息，开始聊天吧！
                                </div>
                            ) : (
                                <div>
                                    {selectedChat.messages.map((msg, index) => (
                                        <div
                                            key={index}
                                            style={{
                                                margin: '10px 0',
                                                padding: '10px',
                                                backgroundColor: msg.role === 'user' ? '#e1f5fe' : '#f1f8e9',
                                                borderRadius: '10px',
                                                maxWidth: '80%',
                                                alignSelf: msg.role === 'user' ? 'flex-end' : 'flex-start',
                                                marginLeft: msg.role === 'user' ? 'auto' : '0'
                                            }}
                                        >
                                            <div><strong>{msg.role === 'user' ? '用户' : 'AI'}</strong></div>
                                            <div>{msg.content}</div>
                                            <div style={{ fontSize: '0.8em', color: '#888', textAlign: 'right' }}>
                                                {new Date(msg.timestamp).toLocaleString()}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>

                        {/* 输入框 */}
                        <div style={{ display: 'flex' }}>
                            <input
                                type="text"
                                value={message}
                                onChange={(e) => setMessage(e.target.value)}
                                style={{ flex: 1, padding: '10px', borderRadius: '5px 0 0 5px' }}
                                placeholder="输入消息..."
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        sendMessage();
                                    }
                                }}
                            />
                            <button
                                onClick={sendMessage}
                                style={{ padding: '10px 20px', borderRadius: '0 5px 5px 0' }}
                            >
                                发送
                            </button>
                        </div>
                    </>
                ) : (
                    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
                        <div style={{ textAlign: 'center' }}>
                            <p>请选择一个聊天或创建新聊天</p>
                            <button onClick={createNewChat}>新建聊天</button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default ChatStore; 